import { ref } from 'vue'

export default () => {
  const projs = ref<ProjModel[]>([])
  const proj = ref<ProjModel>()

  const all = async () => {
    projs.value = await window.api.sql(`select * from projs order by created_at desc`, 'findAll')
  }

  const add = async (data: ProjModel) => {
    return await window.api.sql<number>(
      `insert into projs (company,name,shortName,dianya,created_at) values(@company,@name,@shortName,@dianya,datetime())`,
      'insert',
      {
        company: data.company,
        name: data.name,
        shortName: data.shortName,
        dianya: data.dianya
      }
    )
  }

  const find = async (id: number) => {
    proj.value = await window.api.sql(`select * from projs where id=@id`, 'findOne', {
      id
    })
  }

  const update = async (data: ProjModel) => {
    await window.api.sql(
      `update projs set company=@company,name=@name,shortName=@shortName,dianya=@dianya where id=@id`,
      'update',
      {
        id: data.id,
        company: data.company,
        name: data.name,
        shortName: data.shortName,
        dianya: data.dianya
      }
    )
  }

  return { all, add, find, update, projs, proj }
}
